package com.springboot.securtiy.filter;

import com.springboot.securtiy.exception.VerificationCodeException;
import com.springboot.securtiy.handler.SecurityAuthenticationFailureHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.naming.AuthenticationException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
* Description: 基于过滤器实现图形验证码的验证功能,这属于Servlet层面,简单易理解.<br/>
* date: 2023/12/13 15:35<br/>
* @author: zhangzaijun <br/>
* @since JDK 1.8
*/

@Component
public class VerificationCodeFilter extends OncePerRequestFilter {

    @Autowired
    private SecurityAuthenticationFailureHandler authenticationFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 非登录请求不校验验证码，直接放行
        if(!"/login".equals(request.getRequestURI())){
            filterChain.doFilter(request,response);
        }else {
            try {
                verificationCode(request);
                filterChain.doFilter(request,response);
            } catch (AuthenticationException e) {
                authenticationFailureHandler.onAuthenticationFailure(request,response,e);
            }
        }
    }

    private void verificationCode(HttpServletRequest request) throws AuthenticationException {
        HttpSession session = request.getSession();
        String saveCode = (String) session.getAttribute("captcha");

        if(StringUtils.isEmpty(saveCode)){
            // 随手清除验证码，不管是失败还是成功，所以客户端应在登录失败时刷新验证码
            session.removeAttribute("captcha");
        }

        String inputCode = request.getParameter("captcha");

        if(StringUtils.isEmpty(inputCode) || StringUtils.isEmpty(saveCode) || !saveCode.equals(inputCode)){
            throw new VerificationCodeException();
        }
    }
}
